from fastapi import APIRouter, HTTPException, File, UploadFile
import requests
import datetime
import random
import os
from pathlib import Path
from config import APP_ID, APP_SECRET
from commons.database import Database
from DAL.user import User

router = APIRouter(prefix='/api', tags=['user'])

@router.get('/getopenid')
async def get_openid(code: str):
    """
    通过微信临时登录凭证code获取openid
    :param code: 微信登录返回的临时code
    :return: 包含openid的JSON响应
    """
    # 构建请求URL
    url = f"https://api.weixin.qq.com/sns/jscode2session?appid={APP_ID}&secret={APP_SECRET}&js_code={code}&grant_type=authorization_code"
    try:
        response = requests.get(url)
        data = response.json()
        if "errcode" in data and data["errcode"] != 0:
            return {"error": data["errmsg"], "errcode": data["errcode"]}
        return {"openid": data["openid"]}
    except Exception as e:
        return {"error": str(e)}

@router.post("/users/{user_id}/upload-image")
async def upload_user_image(user_id: int, file: UploadFile = File(...)):
    """
    上传用户图片并更新数据库记录
    :param user_id: 用户ID
    :param file: 上传的图片文件
    :return: 上传结果和文件路径
    """
    # 生成符合要求的文件名（日期+随机秒数）
    date_part = datetime.datetime.now().strftime("%Y%m%d")
    time_part = datetime.datetime.now().strftime("%H%M%S") + f"{random.randint(0, 59):02d}"
    ext = os.path.splitext(file.filename)[1].lower()
    filename = f"{date_part}_{time_part}{ext}"
    
    # 修正路径生成，确保正确使用路径分隔符
    upload_dir = Path("uploads")
    upload_dir.mkdir(exist_ok=True)
    # 确保路径使用正确的分隔符格式
    file_path = str(upload_dir / filename).replace('\\', '/')  # 转换为Unix风格路径分隔符
    
    # 保存文件到指定位置
    with open(file_path, "wb+") as file_object:
        file_object.write(await file.read())
    
    # 获取数据库会话并更新用户记录中的图片路径
    db = next(Database.get_db())
    user = db.query(User).filter(User.id == user_id).first()
    if user:
        user.business_license = file_path  # 存储完整路径
        db.commit()
        return {"message": "Image uploaded successfully", "file_path": file_path}
    else:
        raise HTTPException(status_code=404, detail="用户不存在")